package org.example;

import java.math.BigDecimal;
import java.sql.*;
import java.util.Random;

public class Main {
    // 数据库连接配置，请根据实际情况修改虚拟机中的MySQL地址、端口、数据库名、用户名和密码
    private static final String DB_URL = "jdbc:mysql://192.168.198.101:3306/movie_db?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static final Random random = new Random();

    public static void main(String[] args) {
        try {
            // 加载MySQL JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            // 建立数据库连接
            Connection connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
            System.out.println("成功连接到数据库！");

            // 生成模拟数据
            generateMockData(connection);

            // 关闭连接
            connection.close();
            System.out.println("数据生成完成，已断开数据库连接。");
        } catch (ClassNotFoundException e) {
            System.err.println("找不到MySQL JDBC驱动，请确保已正确添加依赖。");
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("数据库连接或操作失败。");
            e.printStackTrace();
        }
    }

    /**
     * 生成模拟数据
     */
    public static void generateMockData(Connection connection) throws SQLException {
        System.out.println("开始生成模拟数据...");

        // 设置不自动提交事务
        connection.setAutoCommit(false);
        try {
            // 生成电影国家分析数据
            generateMovieCountryAnalysisData(connection, 20);

            // 生成电影类型分析数据
            generateMovieGenreAnalysisData(connection, 15);

            // 生成电影语言分析数据
            generateMovieLanguageAnalysisData(connection, 10);

            // 生成电影热度排行数据
            generateMoviePopularityRankData(connection, 25);

            // 生成电影评分排行数据
            generateMovieRatingRankData(connection, 25);

            // 生成电影发布趋势数据
            generateMovieReleaseTrendsData(connection, 10);

            // 生成城市编码信息数据
            generateCityCodeInfoData(connection, 50);

            // 生成评论信息数据
            generateCommentInfoData(connection, 100);

            // 生成日志信息数据
            generateLogInfoData(connection, 200);

            // 生成权限信息数据
            generatePermissionInfoData(connection, 30);

            // 生成角色信息数据
            generateRoleInfoData(connection, 5);

            // 生成用户信息数据
            generateUserInfoData(connection, 30);

            // 提交事务
            connection.commit();
            System.out.println("所有模拟数据生成完成！");
        } catch (SQLException e) {
            // 发生异常时回滚事务
            connection.rollback();
            System.err.println("数据生成过程中发生错误，已回滚事务: " + e.getMessage());
            throw e;
        } finally {
            // 恢复自动提交模式
            connection.setAutoCommit(true);
        }
    }

    private static void generateMovieCountryAnalysisData(Connection connection, int count) throws SQLException {
        String sql = "INSERT INTO ads_movie_country_analysis (country, value) VALUES (?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] countries = {"美国", "中国", "日本", "韩国", "英国", "法国", "德国", "印度", "加拿大", "澳大利亚", 
                             "巴西", "俄罗斯", "意大利", "西班牙", "墨西哥", "泰国", "瑞典", "荷兰", "土耳其", "阿根廷"};

        for (int i = 0; i < count; i++) {
            ps.setString(1, countries[i % countries.length]);
            ps.setLong(2, random.nextInt(1000000) + 1000);
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条电影国家分析数据");
        } catch (SQLException e) {
            System.err.println("生成电影国家分析数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateMovieGenreAnalysisData(Connection connection, int count) throws SQLException {
        String sql = "INSERT INTO ads_movie_genre_analysis (category_1, value) VALUES (?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] genres = {"动作", "喜剧", "爱情", "科幻", "恐怖", "悬疑", "动画", "剧情", "战争", "奇幻", "冒险", "音乐", "历史", "武侠", "灾难"};

        for (int i = 0; i < count; i++) {
            ps.setString(1, genres[i % genres.length]);
            ps.setLong(2, random.nextInt(1000000) + 1000);
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条电影类型分析数据");
        } catch (SQLException e) {
            System.err.println("生成电影类型分析数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateMovieLanguageAnalysisData(Connection connection, int count) throws SQLException {
        String sql = "INSERT INTO ads_movie_language_analysis (language, value) VALUES (?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] languages = {"中文", "英语", "法语", "德语", "日语", "韩语", "俄语", "西班牙语", "意大利语", "泰语"};

        for (int i = 0; i < count; i++) {
            ps.setString(1, languages[i % languages.length]);
            ps.setLong(2, random.nextInt(1000000) + 1000);
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条电影语言分析数据");
        } catch (SQLException e) {
            System.err.println("生成电影语言分析数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateMoviePopularityRankData(Connection connection, int count) throws SQLException {
        String sql = "INSERT INTO ads_movie_popularity_rank (name, reviews) VALUES (?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] movies = {"复仇者联盟", "阿凡达", "泰坦尼克号", "星球大战", "侏罗纪公园", "狮子王", "冰雪奇缘", "复仇者联盟2", 
                          "复仇者联盟3", "复仇者联盟4", "速度与激情", "变形金刚", "钢铁侠", "蝙蝠侠", "超人", "蜘蛛侠", "X战警", 
                          "黑客帝国", "指环王", "哈利波特", "加勒比海盗", "夺宝奇兵", "终结者", "碟中谍", "007"};

        for (int i = 0; i < count; i++) {
            ps.setString(1, movies[i % movies.length] + (i / movies.length > 0 ? " " + (i / movies.length + 1) : ""));
            ps.setInt(2, random.nextInt(100000) + 1000);
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条电影热度排行数据");
        } catch (SQLException e) {
            System.err.println("生成电影热度排行数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateMovieRatingRankData(Connection connection, int count) throws SQLException {
        String sql = "INSERT INTO ads_movie_rating_rank (name, rating) VALUES (?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] movies = {"肖申克的救赎", "教父", "教父2", "低俗小说", "辛德勒的名单", "十二怒汉", "黑暗骑士", "盗梦空间", 
                          "指环王3", "搏击俱乐部", "黄金三镖客", "阿甘正传", "公民凯恩", "卡萨布兰卡", "北非谍影", "雨人", 
                          "出租车司机", "闪灵", "好家伙", "猎鹿人", "现代启示录", "愤怒的公牛", "疤面煞星", "美国往事", "辛普森一家"};

        for (int i = 0; i < count; i++) {
            ps.setString(1, movies[i % movies.length]);
            ps.setBigDecimal(2, new BigDecimal(8.0 + random.nextDouble() * 2.0).setScale(2, BigDecimal.ROUND_HALF_UP));
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条电影评分排行数据");
        } catch (SQLException e) {
            System.err.println("生成电影评分排行数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateMovieReleaseTrendsData(Connection connection, int count) throws SQLException {
        String sql = "INSERT INTO ads_movie_release_trends (year, value) VALUES (?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        int currentYear = 2025;
        for (int i = 0; i < count; i++) {
            ps.setString(1, String.valueOf(currentYear - count + 1 + i));
            ps.setLong(2, random.nextInt(10000) + 1000);
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条电影发布趋势数据");
        } catch (SQLException e) {
            System.err.println("生成电影发布趋势数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateCityCodeInfoData(Connection connection, int count) throws SQLException {
        String sql = "INSERT INTO t_city_code_info (province, city, code) VALUES (?, ?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] provinces = {"北京市", "上海市", "天津市", "重庆市", "河北省", "山西省", "辽宁省", "吉林省", "黑龙江省", "江苏省", 
                             "浙江省", "安徽省", "福建省", "江西省", "山东省", "河南省", "湖北省", "湖南省", "广东省", "海南省", 
                             "四川省", "贵州省", "云南省", "陕西省", "甘肃省", "青海省", "台湾省", "内蒙古自治区", "广西壮族自治区", "西藏自治区", 
                             "宁夏回族自治区", "新疆维吾尔自治区", "香港特别行政区", "澳门特别行政区"};

        String[] cities = {"北京", "上海", "天津", "重庆", "石家庄", "太原", "沈阳", "长春", "哈尔滨", "南京", 
                          "杭州", "合肥", "福州", "南昌", "济南", "郑州", "武汉", "长沙", "广州", "海口", 
                          "成都", "贵阳", "昆明", "西安", "兰州", "西宁", "台北", "呼和浩特", "南宁", "拉萨", 
                          "银川", "乌鲁木齐", "香港", "澳门"};

        for (int i = 0; i < count; i++) {
            int index = i % provinces.length;
            ps.setString(1, provinces[index]);
            ps.setString(2, cities[index]);
            ps.setString(3, "CODE" + (100000 + i));
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条城市编码信息数据");
        } catch (SQLException e) {
            System.err.println("生成城市编码信息数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateCommentInfoData(Connection connection, int count) throws SQLException {
        String sql = "INSERT INTO t_comment_info (like_num, text, sender_name, sender_avatar, sender_province, receiver_name, receiver_avatar, receiver_province) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] comments = {"这部电影真的很棒！", "剧情紧凑，值得一看", "特效不错，但剧情一般", "演员表演很到位", "有点失望，不如预期", 
                            "强烈推荐，不容错过", "画面精美，故事感人", "节奏稍慢，但值得一观", "经典之作，百看不厌", "适合全家观看"};

        String[] names = {"张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十", "郑一", "王二"};

        String[] provinces = {"北京市", "上海市", "广东省", "江苏省", "浙江省", "四川省", "湖北省", "湖南省", "山东省", "河南省"};

        for (int i = 0; i < count; i++) {
            ps.setInt(1, random.nextInt(1000));
            ps.setString(2, comments[i % comments.length]);
            ps.setString(3, names[i % names.length]);
            ps.setString(4, "avatar_" + (i % 10) + ".jpg");
            ps.setString(5, provinces[i % provinces.length]);
            ps.setString(6, names[(i + 3) % names.length]);
            ps.setString(7, "avatar_" + ((i + 3) % 10) + ".jpg");
            ps.setString(8, provinces[(i + 3) % provinces.length]);
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条评论信息数据");
        } catch (SQLException e) {
            System.err.println("生成评论信息数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateLogInfoData(Connection connection, int count) throws SQLException {
        String sql = "INSERT INTO t_log_info (user_id, nickname, is_login, content, path) VALUES (?, ?, ?, ?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] contents = {"用户登录", "用户登出", "查询数据", "新增数据", "修改数据", "删除数据", "导出报表", "导入数据", "访问首页", "查看详情"};
        String[] paths = {"/login", "/logout", "/query", "/add", "/update", "/delete", "/export", "/import", "/index", "/detail"};
        String[] nicknames = {"管理员", "普通用户", "访客", "测试用户", "开发者"};

        for (int i = 0; i < count; i++) {
            ps.setInt(1, random.nextInt(100) + 1);
            ps.setString(2, nicknames[i % nicknames.length]);
            ps.setInt(3, random.nextInt(2)); // 0 or 1
            ps.setString(4, contents[i % contents.length]);
            ps.setString(5, paths[i % paths.length]);
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条日志信息数据");
        } catch (SQLException e) {
            System.err.println("生成日志信息数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generatePermissionInfoData(Connection connection, int count) throws SQLException {
        // 先清空表数据，避免主键或唯一索引冲突
        PreparedStatement clearPs = connection.prepareStatement("DELETE FROM t_permission_info");
        clearPs.execute();
        clearPs.close();
        
        String sql = "INSERT INTO t_permission_info (title, name, path, orders, icon, pid, x_name, y_name, is_show, descr) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] titles = {"系统管理", "用户管理", "角色管理", "权限管理", "日志管理", "数据统计", "电影分析", "地区分析", "类型分析", "趋势分析"};
        String[] names = {"sys", "user", "role", "perm", "log", "stat", "movie", "area", "type", "trend"};
        String[] paths = {"/sys", "/user", "/role", "/perm", "/log", "/stat", "/movie", "/area", "/type", "/trend"};
        String[] icons = {"sys-icon", "user-icon", "role-icon", "perm-icon", "log-icon", "stat-icon", "movie-icon", "area-icon", "type-icon", "trend-icon"};
        String[] descriptions = {"系统管理模块", "用户管理模块", "角色管理模块", "权限管理模块", "日志管理模块", "数据统计模块", "电影分析模块", "地区分析模块", "类型分析模块", "趋势分析模块"};

        for (int i = 0; i < count; i++) {
            ps.setString(1, titles[i % titles.length]);
            ps.setString(2, names[i % names.length]);
            ps.setString(3, paths[i % paths.length]);
            ps.setInt(4, i); // orders
            ps.setString(5, icons[i % icons.length]);
            ps.setInt(6, i > 0 ? random.nextInt(i) : 0); // pid
            ps.setString(7, "X轴");
            ps.setString(8, "Y轴");
            ps.setInt(9, random.nextInt(2)); // is_show
            ps.setString(10, descriptions[i % descriptions.length]);
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条权限信息数据");
        } catch (SQLException e) {
            System.err.println("生成权限信息数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateRoleInfoData(Connection connection, int count) throws SQLException {
        // 先清空表数据，避免主键或唯一索引冲突
        PreparedStatement clearPs = connection.prepareStatement("DELETE FROM t_role_info");
        clearPs.execute();
        clearPs.close();
        
        String sql = "INSERT INTO t_role_info (name, description, flag, permission_ids) VALUES (?, ?, ?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] roleNames = {"超级管理员", "管理员", "普通用户", "访客", "测试角色"};
        String[] descriptions = {"拥有所有权限", "管理系统用户和基本功能", "普通用户权限", "只读权限", "测试用角色"};
        String[] flags = {"ADMIN_SUPER", "ADMIN", "USER", "GUEST", "TEST"};

        for (int i = 0; i < count; i++) {
            ps.setString(1, roleNames[i % roleNames.length]);
            ps.setString(2, descriptions[i % descriptions.length]);
            ps.setString(3, flags[i % flags.length]);
            // 生成权限ID列表，例如 "1,2,3,4,5"
            StringBuilder permIds = new StringBuilder();
            int permCount = random.nextInt(10) + 1;
            for (int j = 0; j < permCount; j++) {
                if (j > 0) permIds.append(",");
                permIds.append(random.nextInt(30) + 1);
            }
            ps.setString(4, permIds.toString());
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条角色信息数据");
        } catch (SQLException e) {
            System.err.println("生成角色信息数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }

    private static void generateUserInfoData(Connection connection, int count) throws SQLException {
        // 先清空表数据，避免主键或唯一索引冲突
        PreparedStatement clearPs = connection.prepareStatement("DELETE FROM t_user_info");
        clearPs.execute();
        clearPs.close();
        
        String sql = "INSERT INTO t_user_info (username, nickname, password, email, phone, avatar, role) VALUES (?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement ps = connection.prepareStatement(sql);

        String[] usernames = {"admin", "zhangsan", "lisi", "wangwu", "zhaoliu", "sunqi", "zhouba", "wujiu", "zhengshi", "wang er"};
        String[] nicknames = {"管理员", "张三", "李四", "王五", "赵六", "孙七", "周八", "吴九", "郑十", "王二麻子"};
        String[] roles = {"ADMIN", "USER", "USER", "USER", "USER", "USER", "USER", "USER", "USER", "USER"};

        for (int i = 0; i < count; i++) {
            ps.setString(1, usernames[i % usernames.length] + (i / usernames.length > 0 ? i / usernames.length : ""));
            ps.setString(2, nicknames[i % nicknames.length]);
            ps.setString(3, "123456"); // 默认密码
            ps.setString(4, "user" + i + "@example.com");
            ps.setString(5, "138" + String.format("%08d", random.nextInt(100000000)));
            ps.setString(6, "avatar_" + (i % 10) + ".jpg");
            ps.setString(7, roles[i % roles.length]);
            ps.addBatch();
        }

        try {
            ps.executeBatch();
            System.out.println("已生成 " + count + " 条用户信息数据");
        } catch (SQLException e) {
            System.err.println("生成用户信息数据时出错: " + e.getMessage());
            throw e;
        } finally {
            ps.close();
        }
    }
}